package com.sunwayhorizo.health.business.clinic.consultation.query;

import java.util.*;
import javax.ejb.*;
import javax.persistence.*;
import org.jboss.seam.annotations.*;
import com.sunwayhorizo.health.business.base.query.*;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.*;
import com.sunwayhorizo.health.hl7.rim.*;
import com.sunwayhorizo.health.hl7.vocabulary.*;

@Stateless
@Name("ConsultationQuery")
public class ConsultationQuery extends BaseQuery implements ConsultationQueryLocal
{
    private Map<String, Map<String, Object>> conditions = new HashMap<String, Map<String, Object>>();


    @Override
    public List<ActParticipation> findObservationInGroup(String workgroupId, String type, String status, Date from, Date to, int pageSize, int pageNo)
        throws Hl7Exception
    {

        StringBuilder jpql = new StringBuilder();
        jpql.append("select distinct ap from ActParticipation ap left join ap.participationAct act ");
        jpql.append(" left join ap.roleParticipation rp left join act.prtcptnsActList part ");
        jpql.append(" left join rp.roleIiList rii ");
        jpql.append(" where 1=1 ");
        if (StrUtil.isNotEmpty(type))
        {
            jpql.append(" and ap.typeCode=");
            jpql.append(convertInJpql(type));
        }
        jpql.append(" and rii.identifierName=");
        jpql.append(convertInJpql(RoleIICode.DEPTCODE.toString()));
        jpql.append(" and rii.extensionTxt=");
        jpql.append(convertInJpql(workgroupId));
        jpql.append(" and act.codeEtsId=");
        jpql.append(convertInJpql(ActCode.CONSULTATION.code().stringValue()));
        jpql.append(" and act.statusCode=");
        jpql.append(convertInJpql(ActStatus.ACTIVE.code().stringValue()));
        if (StrUtil.isNotEmpty(status))
        {
            jpql.append(" and part.statusCode=");
            jpql.append(convertInJpql(status));
            jpql.append(" and part.typeCode=");
            jpql.append(convertInJpql(ParticipationType.COV.code().stringValue()));
        }

        jpql.append(" and act.activityStartDateTs>=:from ");
        jpql.append(" and act.activityStartDateTs<=:to ");

        Query query = em.createQuery(jpql.toString());

        if (from != null)
        {
            query.setParameter("from", from, TemporalType.TIMESTAMP);
        }
        if (to != null)
        {
            query.setParameter("to", to, TemporalType.TIMESTAMP);
        }

        @SuppressWarnings("unchecked")
        List<ActParticipation> observations = query.setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).getResultList();
        return observations;
    }


    @Override
    public long findCountObservationInGroup(String workgroupId, String type, String status, Date from, Date to) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select count(distinct ap.participationId) from ActParticipation ap left join ap.participationAct act ");
        jpql.append(" left join ap.roleParticipation rp left join act.prtcptnsActList part ");
        jpql.append(" left join rp.roleIiList rii ");
        jpql.append(" where 1=1 ");
        if (StrUtil.isNotEmpty(type))
        {
            jpql.append(" and ap.typeCode=");
            jpql.append(convertInJpql(type));
        }
        jpql.append(" and rii.identifierName=");
        jpql.append(convertInJpql(RoleIICode.DEPTCODE.toString()));
        jpql.append(" and rii.extensionTxt=");
        jpql.append(convertInJpql(workgroupId));
        jpql.append(" and act.codeEtsId=");
        jpql.append(convertInJpql(ActCode.CONSULTATION.code().stringValue()));
        jpql.append(" and act.statusCode=");
        jpql.append(convertInJpql(ActStatus.ACTIVE.code().stringValue()));
        if (StrUtil.isNotEmpty(status))
        {
            jpql.append(" and part.statusCode=");
            jpql.append(convertInJpql(status));
        }
        jpql.append(" and act.activityStartDateTs>=:from ");
        jpql.append(" and act.activityStartDateTs<=:to ");

        Query query = em.createQuery(jpql.toString());

        if (from != null)
        {
            query.setParameter("from", from, TemporalType.TIMESTAMP);
        }
        if (to != null)
        {
            query.setParameter("to", to, TemporalType.TIMESTAMP);
        }
        Long count = (Long) query.getResultList().get(0);
        return count;
    }


    @Override
    public List<ActParticipation> findMyObservation(String emplyeeId, String type, String status, Date from, Date to, int pageSize, int pageNo)
        throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select distinct ap from ActParticipation ap left join ap.participationAct act ");
        jpql.append(" left join ap.roleParticipation rp left join act.prtcptnsActList part ");
        jpql.append(" left join rp.roleIiList rii ");
        jpql.append(" where 1=1 ");
        if (StrUtil.isNotEmpty(type))
        {
            jpql.append(" and ap.typeCode=");
            jpql.append(convertInJpql(type));
        }
        jpql.append(" and rii.identifierName=");
        jpql.append(convertInJpql(RoleIICode.EMPLOYEEID.toString()));
        jpql.append(" and rii.extensionTxt=");
        jpql.append(convertInJpql(emplyeeId));
        jpql.append(" and act.codeEtsId=");
        jpql.append(convertInJpql(ActCode.CONSULTATION.code().stringValue()));
        jpql.append(" and act.statusCode=");
        jpql.append(convertInJpql(ActStatus.ACTIVE.code().stringValue()));
        if (StrUtil.isNotEmpty(status))
        {
            jpql.append(" and part.statusCode=");
            jpql.append(convertInJpql(status));
            jpql.append(" and part.typeCode=");
            jpql.append(convertInJpql(ParticipationType.PRCP.code().stringValue()));
        }
        else if (ParticipationType.PRCP.code().stringValue().equals(type))
        {
            jpql.append(" and part.statusCode in (");
            jpql.append(convertInJpql(ParticipationStatus.ACCEPT.code().stringValue()));
            jpql.append(",");
            jpql.append(convertInJpql(ParticipationStatus.COMPLETE.code().stringValue()));
            jpql.append(")");
            jpql.append(" and part.typeCode=");
            jpql.append(convertInJpql(ParticipationType.PRCP.code().stringValue()));
        }
        jpql.append(" and act.activityStartDateTs>=:from ");
        jpql.append(" and act.activityStartDateTs<=:to ");

        Query query = em.createQuery(jpql.toString());

        if (from != null)
        {
            query.setParameter("from", from, TemporalType.TIMESTAMP);
        }
        if (to != null)
        {
            query.setParameter("to", to, TemporalType.TIMESTAMP);
        }

        @SuppressWarnings("unchecked")
        List<ActParticipation> observations = query.setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).getResultList();
        return observations;
    }
    
    @Override
    public long findCountMyObservation(String emplyeeId, String type, String status, Date from, Date to) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select count(distinct ap) from ActParticipation ap left join ap.participationAct act ");
        jpql.append(" left join ap.roleParticipation rp left join act.prtcptnsActList part ");
        jpql.append(" left join rp.roleIiList rii ");
        jpql.append(" where 1=1 ");
        if (StrUtil.isNotEmpty(type))
        {
            jpql.append(" and ap.typeCode=");
            jpql.append(convertInJpql(type));
        }
        jpql.append(" and rii.identifierName=");
        jpql.append(convertInJpql(RoleIICode.EMPLOYEEID.toString()));
        jpql.append(" and rii.extensionTxt=");
        jpql.append(convertInJpql(emplyeeId));
        jpql.append(" and act.codeEtsId=");
        jpql.append(convertInJpql(ActCode.CONSULTATION.code().stringValue()));
        jpql.append(" and act.statusCode=");
        jpql.append(convertInJpql(ActStatus.ACTIVE.code().stringValue()));
        if (StrUtil.isNotEmpty(status))
        {
            jpql.append(" and part.statusCode=");
            jpql.append(convertInJpql(status));
            jpql.append(" and part.typeCode=");
            jpql.append(convertInJpql(ParticipationType.PRCP.code().stringValue()));
        }
        else if (ParticipationType.PRCP.code().stringValue().equals(type))
        {
            jpql.append(" and part.statusCode in (");
            jpql.append(convertInJpql(ParticipationStatus.ACCEPT.code().stringValue()));
            jpql.append(",");
            jpql.append(convertInJpql(ParticipationStatus.COMPLETE.code().stringValue()));
            jpql.append(")");
            jpql.append(" and part.typeCode=");
            jpql.append(convertInJpql(ParticipationType.PRCP.code().stringValue()));
        }
        jpql.append(" and act.activityStartDateTs>=:from ");
        jpql.append(" and act.activityStartDateTs<=:to ");

        Query query = em.createQuery(jpql.toString());

        if (from != null)
        {
            query.setParameter("from", from, TemporalType.TIMESTAMP);
        }
        if (to != null)
        {
            query.setParameter("to", to, TemporalType.TIMESTAMP);
        }
        Long count = (Long) query.getResultList().get(0);
        return count;
    }



    @Override
    public List<ActParticipation> findParitcipationsByConsultationId(String consultationId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> act = new HashMap<String, Object>();
        act.put("codeEtsId", ActCode.CONSULTATION.code().stringValue());
        act.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("act", act);

        Map<String, Object> part = new HashMap<String, Object>();
        part.put("signatureCodeEtsId", consultationId);
        conditions.put("part", part);

        @SuppressWarnings("unchecked")
        List<ActParticipation> observations = em.createQuery(constructJbql(conditions, Observation.class, null, "part")).getResultList();

        if (observations.isEmpty())
        {
            log.info("findObservationByConsultationId-根据会诊单号查询参与为空！");
            return null;
        }
        return observations;
    }


    @Override
    public Observation findObservationByConsultationId(String consultationId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> act = new HashMap<String, Object>();
        act.put("codeEtsId", ActCode.CONSULTATION.code().stringValue());
        act.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("act", act);

        Map<String, Object> part = new HashMap<String, Object>();
        part.put("signatureCodeEtsId", consultationId);
        conditions.put("part", part);

        @SuppressWarnings("unchecked")
        List<Observation> observations = (List<Observation>) queryResults(conditions, Observation.class, 1, 1);

        if (observations.isEmpty())
        {
            log.info("findObservationByConsultationId-根据会诊单号查询激活会诊单为空！");
            return null;
        }
        return observations.get(0);
    }
}
